/**
 * Created by zhangwenlei on 2017/4/28.
 */
var express = require('express');
var path = require('path');
var router = express.Router();
var http = require('http');
var fs=require('fs');
var spawn=require('child_process').spawn;

router.post('/',function (req, res) {
    var postData = "";
    req.setEncoding("utf8");
    req.addListener("data", function(data) {
        postData += data;
    });
    req.addListener("end",function () {
       if(postData){
           fs.writeFile(path.join(__dirname,'..','..','mvc-new','bundles','bundle','model','test.json'),postData,function (err) {
               if(err){
                   res.end('error');
               }else{
                   var options = {
                       port: 3005,
                       path: '/compile',
                       method: 'post',
                       headers: {
                           'Content-Type': 'application/json'
                       }
                   };
                   var reqData = {
                       compilerid:'bcp',
                       jsonPath: path.join(__dirname, '..', '..', 'mvc-new', 'bundles', 'bundle', 'model', 'test.json'),
                       bundleFolderPath:path.join(__dirname, '..', '..', 'mvc-new', 'bundles', 'bundle'),
                       outputFolder:'target'
                   };
                   var serverRequest = http.request(options, function(response) {
                       // response.pipe(res);
                       // if(response=='compile completed') {
                           if (this.child) {
                               this.child.kill('SIGTERM');
                               this.child = null;
                           }
                           this.child = spawn('node', ["index.js"], {cwd: path.join(__dirname, '..', '..', 'mvc-new')});
                           res.end('success');
                       // }
                   });
                   serverRequest.write(JSON.stringify(reqData));
                   serverRequest.end();
               }
           });
       }
    });
});
module.exports=router;